<template>
  <div>
    <!-- 资源导航区域 -->
    <van-sticky offset-top="0">
      <van-cell
        v-if="folderStack.length > 0"
        value=""
        style="margin-top: 0.2rem;background-color: #E6E6E6;"
      >
        <template #icon>
          <a
            class="cf-link"
            @click="toPrevFolder"
          > <span><van-icon name="arrow-left" /> 上一级</span> </a>
        </template>
      </van-cell>
    </van-sticky>

    <!-- 资源列表区域 -->
    <van-cell-group
      v-for="f in fileAndFolderList"
      :key="f.id"
      style="margin-top: 0.2rem;"
    >
      <van-cell
        :title="f.fileName"
        :icon="getFileIconUrl(f)"
        :label="f.typeName"
        clickable
        @click="getFile(f)"
      />
    </van-cell-group>

  </div>
</template>

<script>
import { getFileIconName } from '@/utils/file'
import { Cell, CellGroup, Sticky, NavBar } from 'vant'
import { getRootFolder, listByFolderId } from '@/api/bussiness/course/courseResource'

export default {
  name: 'CourseResourceList',
  components: {
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Sticky.name]: Sticky,
    [NavBar.name]: NavBar
  },
  data () {
    return {
      folderStack: [], // 目录栈
      courseId: 5, // 课程编号
      currentFolderId: null, // 当前的目录id
      fileAndFolderList: [ // 当前目录下的所有文件和文件夹
      ]
    }
  },
  created () {
    this.courseId = Number.parseInt(this.$route.query.courseId)
    // 获取课程下对应的根目录
    getRootFolder(this.courseId).then(({ data }) => {
      const rootFolderId = data.id
      this.currentFolderId = rootFolderId
      // 获取资源列表
      this.refreshResourceList(rootFolderId)
    })
  },
  methods: {
    getFileIconUrl (file) { // 获取文件的图标url
      const { fileName, typeId } = file
      return `images/courseRes/${getFileIconName(typeId, fileName)}.svg`
    },
    refreshResourceList (fId) {
      listByFolderId(fId).then(({ data }) => {
        this.fileAndFolderList = data
      })
    },
    toPrevFolder () { // 回到上一级目录
      const size = this.folderStack.length
      const preFolderId = this.folderStack[size - 1]
      // 获取preFolderId 下的资源列表
      this.refreshResourceList(preFolderId)
      this.folderStack = this.folderStack.slice(0, size - 2)
      this.currentFolderId = preFolderId
    },
    toNextFolder (folder) { // 进入选中的目录
      this.folderStack.push(this.currentFolderId)
      this.currentFolderId = folder.id
      this.refreshResourceList(folder.id)
    },
    getFile (f) { // 下载文件或进入下一级目录
      if (f.isFolder) {
        this.toNextFolder(f)
      } else {
        // 下载文件
        window.open(f.url)
      }
    }

  }
}
</script>

<style scoped>
.cf-link :active {
  color: #6a47fc;
}
</style>
